package com.paypalpay.controller.interfaces;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.paypalpay.external.entity.queryorder.request.RequestQueryorder;
import com.paypalpay.external.entity.queryorder.request.RequestQueryorderDate;
import com.paypalpay.external.entity.queryorder.response.ResponseQueryorder;
import com.paypalpay.external.entity.queryorder.response.ResponseQueryorderData;
import com.paypalpay.external.entity.queryorder.response.ResponseQueryorderTradeData;
import com.paypalpay.external.utils.UtilsInterfacesPackage;
import com.paypalpay.pojo.response.responseBody.QueryOrderResponseBody;
import com.paypalpay.pojo.response.subResponse.common.PackageOrder;
import com.paypalpay.pojo.response.subResponse.common.RefuelingPackageList;
import com.paypalpay.service.InternationalPayPackageService;
import com.paypalpay.service.PartnerService;
import com.paypalpay.service.SequenceService;
import com.paypalpay.turntointerfaceservice.TrunToQueryorderService;
import com.paypalpay.util.wx.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 查询当前设备所有的订单
 *
 * @author lm
 * @date 2018/8/31
 */
@RestController
@Api(value = "查询当前设备所有的订单接口")
public class QueryDeviceOrderController {
    @Autowired
    HttpSession session;
    @Autowired
    SequenceService sequenceService;
    @Autowired
    InternationalPayPackageService internationalPayPackageService;
    @Autowired
    PartnerService partnerService;

    @CrossOrigin
    @RequestMapping(value = "/queryPackageOrder", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询订单", response = ResponseQueryorder.class)
    public String queryOrder(@ApiParam @RequestBody RequestQueryorder requestQueryorder) {

        String requestStr = JSON.toJSONString(requestQueryorder);
        System.out.println("前端请求报文是：" + requestStr);
        // 1，生成流水号
        String ConnSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());

        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();

        requestQueryorder = JSONArray.parseObject(requestStr, RequestQueryorder.class);

        String requestSign = requestQueryorder.getSign();
        if (requestQueryorder.getSign() == null) {
            System.out.println("请求报文不合法:sign为空");
            String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
            return jsonString;
        } else {
            System.out.println("请求的签名是：" + requestSign);
            RequestQueryorderDate requestData = requestQueryorder.getData();
            if (requestQueryorder.getData() == null) {
                System.out.println("请求报文不合法:data为空");
                String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
                return jsonString;
            } else {
                String partnerCode = requestData.getPartnerCode();
                String secret = partnerService.findSecretByPartnerCode(partnerCode);
                String connSeqNo = requestData.getConnSeqNo();
                String token = requestData.getToken();
                String tradeTime = requestData.getTradeTime();
                String tradeType = requestData.getTradeType();
                String lang = requestData.getLang();
                if (requestData.getTradeData() == null) {
                    System.out.println("请求报文不合法:TradeData为空");
                    String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
                    return jsonString;
                } else {
                    // 将请求体json转成String
                    String str = JSON.toJSONString(requestData);
                    // 将Str拿去计算签名
                    String sign = utils.calculateSignature(str);
                    System.out.println("计算的签名是：" + sign);

                    String deviceId = requestData.getTradeData().getDeviceId();
                    String deviceType = requestData.getTradeData().getDeviceType();

                    if (deviceId == null || deviceId.length() <= 0 || deviceType == null || deviceType.length() <= 0) {
                        //参数不全,回复报文
                        System.out.println("请求报文不合法:参数不全！");
                        String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
                        return jsonString;
                    } else {
                        //参数是齐全的验证签名：
                        if (!requestSign.equalsIgnoreCase(sign)) {
                            // 如果收到的签名跟算出的签名相同才可以回复正确的报文
                            String jsonString = utils.publicMessage(ConnSeqNo, tradeTime, partnerCode, token, tradeType);
                            return jsonString;
                        } else {
                            //参数齐全，而且签名通过
                            //2:拿着现在有的数据去北北京下正式的单
                            TrunToQueryorderService trunToQueryorderService = new TrunToQueryorderService();
                            QueryOrderResponseBody responseBody = trunToQueryorderService.queryOrder(partnerCode, deviceId, deviceType, secret);

                            if (responseBody == null) {
                                ResponseQueryorderData data = new ResponseQueryorderData();
                                data.setConnSeqNo(ConnSeqNo);
                                data.setPartnerCode(partnerCode);
                                data.setToken(token);
                                data.setTradeType(tradeType);
                                data.setTradeTime(tradeTime);
                                data.setTradeRstCode(1003);
                                data.setTradeRstMessage("未查询到数据");

                                ResponseQueryorder responseQueryorder = new ResponseQueryorder();
                                responseQueryorder.setData(data);
                                responseQueryorder.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                // 返回给调用者的报文
                                String jsonString = JSON.toJSONString(responseQueryorder);
                                System.out.println("响应报文：" + jsonString);
                                return jsonString;
                            } else {
                                List<PackageOrder> orderList = new ArrayList<PackageOrder>();
                                List<ResponseQueryorderTradeData> tradeData = new ArrayList<ResponseQueryorderTradeData>();
                                ResponseQueryorderTradeData tra = null;
                                //从body中取出多个Package_order
                                orderList = responseBody.getPackageOrder();
                                //这里需要做一下判空的处理
                                if (orderList == null) {
                                    //等于null
                                    ResponseQueryorderData data = new ResponseQueryorderData();
                                    data.setConnSeqNo(ConnSeqNo);
                                    data.setPartnerCode(partnerCode);
                                    data.setToken(token);
                                    data.setTradeType(tradeType);
                                    data.setTradeTime(tradeTime);
                                    data.setTradeRstCode(1003);
                                    data.setTradeRstMessage("未查询到数据");
                                    data.setTradeData(tradeData);

                                    ResponseQueryorder responseQueryorder = new ResponseQueryorder();
                                    responseQueryorder.setData(data);
                                    responseQueryorder.setSign(MD5.calcMD5(JSON.toJSONString(data)));

                                    // 返回给调用者的报文
                                    String jsonString = JSON.toJSONString(responseQueryorder);
                                    System.out.println("响应报文：" + jsonString);
                                    return jsonString;
                                } else {
                                    for (PackageOrder order : orderList) {
                                        String orderId = order.getOrderCode();
                                        System.out.println("到底有没有拿到数据：" + orderId);
                                        String deviceIds = order.getDeviceId();
                                        String packageCode = order.getPackageCode();
                                        String packageName = order.getPackageName();
                                        String packageNameEN = internationalPayPackageService.queryPackageName(packageName, partnerCode);
                                        String packageType = order.getPackageType();
                                        String orderStatus = order.getOrderStatus();

                                        String buyType = order.getBuyType();
                                        String orderPeriod = order.getOrderPeriod();
                                        String flow = order.getFlow();
                                        String usedFlow = order.getUsedFlow();
                                        String flowUseRate = order.getFlowUseRate();
                                        String orderUsedFlow = order.getOrderUsedFlow();

                                        String orderDate = order.getOrderDate();
                                        String activeDate = order.getActiveDate();
                                        String expireDate = order.getExpireDate();
                                        String isOrderRefuelingPackage = order.getIsOrderRefuelingPackage();

                                        List<RefuelingPackageList> refuelingPackageList = order.getRefuelingPackageList();
                                        for (RefuelingPackageList re : refuelingPackageList) {
                                            String refPackageName = re.getRefPackageName();
                                            String refPackageCode = re.getRefPackageCode();
                                            String refPackageFlow = re.getRefPackageFlow();
                                            String refpackageOrderDate = re.getRefpackageOrderDate();

                                            if (orderId != null) {
                                                tra = new ResponseQueryorderTradeData();
                                                tra.setOrderId(orderId);
                                                tra.setPackageCode(packageCode);

                                                if (lang.equals("en")) {

                                                    tra.setPackageName(packageNameEN);
                                                } else {

                                                    tra.setPackageName(packageName);
                                                }
                                                tra.setPackageType(packageType);
                                                tra.setOrderStatus(orderStatus);
                                                tra.setOrderStartDate("");
                                                tra.setOrderPlannedEndDate("");
                                                tra.setOrderActualEndDate("");
                                                tradeData.add(tra);
                                            }
                                        }

                                    }
                                    //循环结束了
                                    ResponseQueryorderData data = new ResponseQueryorderData();
                                    data.setConnSeqNo(ConnSeqNo);
                                    data.setPartnerCode(partnerCode);
                                    data.setToken(token);
                                    data.setTradeType(tradeType);
                                    data.setTradeTime(tradeTime);
                                    data.setTradeRstCode(1000);
                                    data.setTradeRstMessage("成功");
                                    data.setTradeData(tradeData);

                                    ResponseQueryorder responseQueryorder = new ResponseQueryorder();
                                    responseQueryorder.setData(data);
                                    responseQueryorder.setSign(MD5.calcMD5(JSON.toJSONString(data)));

                                    // 返回给调用者的报文
                                    String jsonString = JSON.toJSONString(responseQueryorder);
                                    System.out.println("响应报文：" + jsonString);
                                    return jsonString;
                                }

                            }
                        }

                    }
                }
            }
        }
    }
}